import { DavinciImage } from './custom-types.ts';
import { h, VNode } from 'snabbdom';
import { IDomEditor, SlateElement, DomEditor, SlateTransforms } from '@wangeditor/editor';
// import { MENU_KEY } from './menu/index.ts'
/**
 * 渲染“附件”元素到编辑器
 * @param elem 附件元素，即上文的 myResume
 * @param children 元素子节点，void 元素可忽略
 * @param editor 编辑器实例
 * @returns vnode 节点（通过 snabbdom.js 的 h 函数
 */

export function renderDavinciBlock(elem: SlateElement, children: VNode[] | null, editor: IDomEditor): VNode {
	const { color = '#000', selectedColor = '#000', backgroundColor = 'rgba(0,0,0,0.1)', style = {}, src, alt, href } = elem as unknown as DavinciImage;

	let { width = '', height = 'auto' } = style;

	let reverse = false;
	let originalX = 0;
	let originalWidth = 0;
	let originalHeight = 0;

	let targetEl: HTMLDivElement | null = null;

	const selected = DomEditor.isNodeSelected(editor, elem);

	const config = editor.getConfig();

	const onMousemove = (e: MouseEvent) => {
		e.preventDefault();

		const { clientX } = e;
		const gap = reverse ? originalX - clientX : clientX - originalX;
		const newWidth = originalWidth + gap;
		const newHeight = (newWidth * originalHeight) / originalWidth;

		if (targetEl == null) return;
		if (newWidth <= 30 && newHeight <= 30) return;
		targetEl.style.width = newWidth + 'px';
		targetEl.style.height = newHeight + 'px';
	};

	const onMouseup = () => {
		document.removeEventListener('mousemove', onMousemove);
		if (targetEl == null) return;
		const newWidth = targetEl.style.width;
		const newHeight = targetEl.style.height;

		// 修改 node
		const props = {
			style: {
				...style,
				width: newWidth,
				height: newHeight
			}
		};
		SlateTransforms.setNodes(editor, props, { at: DomEditor.findPath(editor, elem) });

		document.removeEventListener('mouseup', onMouseup);
	};
	const init = (e: MouseEvent) => {
		originalX = e.clientX;

		document.addEventListener('mousemove', onMousemove);

		document.addEventListener('mouseup', onMouseup);
	};

	const imageVnode = h(
		'div',
		{
			props: { contentEditable: false, draggable: true }, // HTML 属性，驼峰式写法
			style: { width, height, display: 'inline-block', verticalAlign: 'bottom' },
			src: src,
			alt,
			attrs: {
				class: 'davinci-image-inner'
			}
		},
		[
			h('img', {
				style: { width: '100%', height: 'auto', display: 'inline-block', verticalAlign: 'bottom' },
				src: src,
				alt,
				attrs: {
					class: 'davinci-image-inner'
					// alt: alt
				}
			})
		]
	);

	const imageHandles = h(
		'div',
		{
			style: {
				position: 'absolute',
				display: selected ? 'block' : 'none',
				width: '100%',
				height: '100%',
				left: '0',
				top: '0',
				border: '1px solid transparent'
			},
			attrs: {
				class: 'davinci-image-handles'
			},
			on: {
				mousedown(e: MouseEvent) {
					let target = e.target as HTMLDivElement;
					if (!target.classList.contains('w-e-image-dragger')) {
						return;
					}
					e.preventDefault();
					let classList = target.classList;
					if (classList.contains('left-top') || classList.contains('left-bottom')) {
						reverse = true;
					}
					targetEl = target.parentElement?.previousSibling as HTMLDivElement;
					originalWidth = targetEl?.clientWidth;
					originalHeight = targetEl?.clientHeight;
					init(e);
				}
			}
		},
		[
			h('div', { attrs: { class: 'w-e-image-dragger left-top' } }, ''),
			h('div', { attrs: { class: 'w-e-image-dragger right-top' } }, ''),
			h('div', { attrs: { class: 'w-e-image-dragger left-bottom' } }, ''),
			h('div', { attrs: { class: 'w-e-image-dragger right-bottom' } }, '')
		]
	);
	const davinciVnode = h(
		'div',
		{
			props: { contentEditable: false, draggable: true }, // HTML 属性，驼峰式写法
			style: {
				display: 'inline-block',
				padding: '0',
				margin: '0 1px',
				animation: selected ? 'davinci-block-blink 1s linear 0s infinite' : 'none',
				position: 'relative',
				verticalAlign: style?.verticalAlign ?? 'middle'
				// boxSizing: 'content-box'
			},
			dataset: { type: 'davinci-image' },
			attrs: {
				class: 'davinci-image-container w-e-image-container',
				draggable: 'true'
			},
			on: {
				// mousedown(e) {
				//   (e.target as HTMLSpanElement).setAttribute('draggable', "true")
				// },
				// mouseup(e) {
				//   (e.target as HTMLSpanElement).removeAttribute('draggable')
				// },
				// click(e) {
				//   config.MENU_CONF?.['davinci-link'].onClickHandle?.(link, content)
				// }
			}
		},
		selected ? [imageVnode, imageHandles] : [imageVnode]
	);

	const davinciBlockVnode = h(
		'span',
		{
			props: { contentEditable: false },
			style: {
				display: 'inline-block',
				padding: '0 3px',
				margin: '0 1px',
				color: selected ? selectedColor : color,
				background: backgroundColor ?? 'rgba(0,0,0,0.1)',
				animation: selected ? 'davinci-block-blink 1s linear 0s infinite' : 'none',
				fontWeight: 'bold',
				cursor: 'pointer',
				userSelect: 'none'
			},
			on: {
				// mousedown(e) {
				// 	(e.target as HTMLSpanElement).setAttribute('draggable', 'true');
				// },
				// mouseup(e) {
				// 	(e.target as HTMLSpanElement).removeAttribute('draggable');
				// },
				async contextmenu(e) {
					e.preventDefault();
					let res = await config.EXTEND_CONF?.['davinci-image']?.onRightClick?.(elem);
					if (res) {
						SlateTransforms.removeNodes(editor, {
							match: n => DomEditor.checkNodeType(n, 'davinci-image')
						});
					}
				},
				click() {
					const { children, ...rest } = elem;
					config.EXTEND_CONF?.['davinci-image']?.onClick?.(rest);
				}
				// click(e) {
				//   config.MENU_CONF?.['davinci-link'].onClickHandle?.(link, content)
				// }
			}
		},
		`{图片：${alt}}`
	);
	return config.viewMode == 1 ? davinciBlockVnode : davinciVnode;
}

const conf = {
	type: 'davinci-image', // 节点 type ，重要！！！
	renderElem: renderDavinciBlock
};

export default conf;
